package com.xing.springbootdemo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xing.springbootdemo.common.Result;
import com.xing.springbootdemo.entity.Consumer;
import com.xing.springbootdemo.mapper.ConsumerMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @Author: caidaxing
 * @Date: 2021/12/27/20:00
 * @Description:
 */
@RestController
@RequestMapping("/consumer")
public class ConsumerController {

    Logger logger = LoggerFactory.getLogger(ConsumerController.class);

    @Resource
    ConsumerMapper consumerMapper;

    /**
     * 登录
     * @param consumer
     * @return
     */
    @PostMapping("/login")
    public Result<?> login(@RequestBody Consumer consumer) {
        Consumer res = consumerMapper.selectOne(Wrappers.<Consumer>lambdaQuery().eq(Consumer::getUsername, consumer.getUsername()).eq(Consumer::getPassword, consumer.getPassword()));
        if(res == null) {
            logger.info("用户名或密码错误");
            return Result.failed("用户名或密码错误");
        }
        if(!consumer.getRole().equals(res.getRole())) {
            logger.info("登录权限错误");
            return Result.failed("登录权限错误");
        }
        return Result.successWithData(res);
    }

    /**
     * 获取最新用户信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Long id) {
        return Result.successWithData(consumerMapper.selectById(id));
    }

    /**
     * 注册
     * @param consumer
     * @return
     */
    @PostMapping("/register")
    public Result<?> register(@RequestBody Consumer consumer) {
        Consumer res = consumerMapper.selectOne(Wrappers.<Consumer>lambdaQuery().eq(Consumer::getUsername, consumer.getUsername()));
        if(res != null) {
            logger.info("用户名重复");
            return Result.failed("用户名重复");
        }
        if (consumer.getPassword() == null) {
            consumer.setPassword("123456");
        }
        consumerMapper.insert(consumer);
        return Result.successWithoutData();
    }

    /**
     * 新增用户
     * @param consumer
     * @return
     */
    @PostMapping
    public Result<?> save(@RequestBody Consumer consumer) {
        if (consumer.getPassword() == null) {
            consumer.setPassword("123456");
        }
        try {
            consumerMapper.insert(consumer);
            return Result.successWithoutData();
        }catch (Exception e) {
            logger.info("新增失败");
            return Result.failed("新增失败");
        }
    }

    /**
     * 更新用户信息
     * @param consumer
     * @return
     */
    @PutMapping
    public Result<?> update(@RequestBody Consumer consumer) {
        int i = consumerMapper.updateById(consumer);
        if (i == 1) {
            return Result.successWithoutData();
        }
        logger.info("更新异常");
        return Result.failed("更新异常");
    }

    /**
     * 删除信息
     * @param id @PathVariable 注解来实现数据的获取
     * @return
     */
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        int i = consumerMapper.deleteById(id);
        if (i == 1) {
            return Result.successWithoutData();
        }
        logger.info("删除异常");
        return Result.failed("删除异常");
    }

    /**
     * 用户分页列表查询，包含书籍表的一对多查询
     * @param pageNum
     * @param pageSize
     * @param search
     * @return
     */
    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search) {
        // 模糊查询（昵称为 NULL ）也能匹配到数据
        LambdaQueryWrapper<Consumer> wrapper = Wrappers.<Consumer>lambdaQuery();
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(Consumer::getNickName, search);
        }
        Page<Consumer> consumerPage = consumerMapper.findPage(new Page<>(pageNum, pageSize), search);
        return Result.successWithData(consumerPage);
    }
}
